package com.nervenets.web.controller.handler.admin.movie;

import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.MovieStatus;
import com.nervenets.web.enumeration.Role;
import com.nervenets.web.hibernate.domain.film.Movie;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

public class MovieProfitHandler extends SessionHandler<MovieProfitParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.issues();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(MovieProfitParams params, HttpServletRequest request) throws Exception {
        return (String) redisSyncLocker.idLock(params.getMovieId(), o -> {
            final Movie movie = userDao.findById(params.getMovieId(), Movie.class);
            if (null == movie) return errorMessage(MessageCode.code_404, "影片不存在");

            if (!(MovieStatus.bonus.equals(movie.getStatus()) || MovieStatus.pause.equals(movie.getStatus()))) {
                return errorMessage(MessageCode.code_444, "影片还未售罄或停售");
            }

            movie.getInfo().setProfit(params.getProfit());
            movie.getInfo().setProfitFailedReason(null);
            userDao.saveOrUpdate(movie);
            return successMessage(movie);
        });
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
